#include "log.hpp"
#include <string>
#include <cstring>
#include <sys/fcntl.h>
#include <unistd.h>

int main()
{
    // 用于接受管道通信读端和写端文件描述符的fd
    int pipefd[2] = { 0 };

    // 创建管道
    int ret = pipe(pipefd);
    if(ret < 0)
    {
        // 检查管道创建是否成功
        logMessage(FATAL, "Create pipe fail, errno:%d, errMsg:%s\n", errno, strerror(errno));
        exit(1);
    }

    // 创建子进程
    pid_t id = fork();
    if(id < 0)
    {
        logMessage(FATAL, "Fork fail, errno:%d, errMsg:%s\n", errno, strerror(errno));
        exit(2);
    }

    // 子进程代码，负责读取数据，
    if(id > 0)
    {
        close(pipefd[1]);    // 关闭写端文件描述符
        char buffer[1024];   // 读取缓冲区

        while(true)
        {
            ssize_t n = read(pipefd[0], buffer, 1023);
            if(n > 0)
            {
                buffer[n] = '\0';    // 添加字符串末尾'\0'
                logMessage(NORMAL, "Child process read message success# %s\n", buffer);
            }
            else if(n == 0)
            {
                logMessage(DEBUG, "Peer close, me close!\n");
                break;
            }
            else
            {
                logMessage(ERROR, "Read message fail!\n");
                break;
            }
        }

        close(pipefd[0]);
        exit(0);
    }

    // 父进程代码，负责写数据
    close(pipefd[0]);   // 关闭读端文件描述符
    std::string Message("I am father Process");

    // 连发5次信息，每次间隔1s
    int cnt = 5;
    while(cnt--)
    {
        ssize_t n = write(pipefd[1], Message.c_str(), Message.size());
        if(n < 0)
        {
            logMessage(NORMAL, "Write message fail, errno:%d, errMsg:%s\n", errno, strerror(errno));
        }
        sleep(1);
    }

    close(pipefd[1]);

    return 0;
}